<template>
	<view class="baseForm">
		<!-- 新增未完成！！！！！！！！！！！！！！！！！！ -->
		<u--form labelPosition="left" :model="umodel" :rules="rules" ref="uForm" class="form" labelWidth="160rpx"
			errorType="toast">
			<!-- 			<u-form-item label="工厂">
				<u--input v-model="umodel.plantCode" placeholder="请填写工厂" inputAlign="right" clearable :disabled="true"
					border="none"></u--input>
			</u-form-item>
			<u-form-item label="工作中心">
				<u--input v-model="umodel.workCenterName" placeholder="请填写工作中心" inputAlign="right" clearable
					:disabled="true" border="none"></u--input>
			</u-form-item>
			<u-form-item label="班组">
				<u--input v-model="umodel.crewName" placeholder="请填写班组" inputAlign="right" clearable :disabled="true"
					border="none"></u--input>
			</u-form-item> -->
			<u-form-item label="报工类型" prop="unscheduledReportTypeName">
				<u--input v-model="umodel.unscheduledReportTypeName" inputAlign="right" placeholder="请填写报工类型" clearable
					border="none" @click="storageLocationShow = true" :disabled="true"></u--input>
			</u-form-item>

			<u-form-item label="开工时间" prop="startTime" @click="openTimeSelect">
				{{umodel.startTime}}
				<u--input v-model="umodel.startTime" border="none" inputAlign="right" disabled disabledColor="#ffffff"
					v-if="false" placeholder="请选择时间"></u--input>
				<u-datetime-picker :show="show" v-model="umodel.startTimeA" mode="datetime" @cancel="show = false"
					@confirm="timeSelect"></u-datetime-picker>
			</u-form-item>
			<u-form-item label="完工时间" prop="completeTime" @click="openTimeSelect1">
				{{umodel.completeTime}}
				<u--input v-model="umodel.completeTime" border="none" inputAlign="right" disabled v-if="false"
					disabledColor="#ffffff" placeholder="请选择时间"></u--input>
				<u-datetime-picker :show="show1" v-model="umodel.completeTimeA" mode="datetime" @cancel="show1 = false"
					@confirm="timeSelect1"></u-datetime-picker>
			</u-form-item>
			<!-- 			<u-form-item label="总工时/分" prop="totalTime">
				<u--input v-model="umodel.totalTime" inputAlign="right" clearable border="none"
					:disabled="true"></u--input>
			</u-form-item> -->
			<u-form-item label="中断时长/分" prop="totalTime" label-width="90">
				<u--input v-model="umodel.totalTime" inputAlign="right" placeholder="请填中断时长" clearable
					border="none"></u--input>
			</u-form-item>
			设备号、零件号、工序等特殊说明：
			<u-form-item prop="unscheduledReportContent">
				<!-- 				<u--input v-model="umodel.unscheduledReportContent" inputAlign="right" clearable
					border="none"></u--input> -->
				<u-textarea v-model="umodel.unscheduledReportContent" placeholder="请输入内容" count
					maxlength="100"></u-textarea>
			</u-form-item>
		</u--form>
		<u-picker :show="storageLocationShow" :columns="storageLocationList" @cancel="storageLocationShow = false"
			@confirm="handelStorageLocation" keyName="label"></u-picker>
		<!-- 提交按钮 -->
		<button type="primary" @click="submit" class="submit_btn" :loading="posting"
			v-if="one.reportState==0 || one.reportState==3">
			填报
		</button>
		<button type="primary" @click="deleted" class="submit_btn" :loading="posting"
			v-if="one.unscheduledReportId && (one.reportState==0 || one.reportState==3)">
			删除
		</button>
	</view>
	<u-modal :show="showImport" ref="uModal" :content="`请确认是否对当非生产报工详情进行删除？`" :confirmText="selectState"
		showCancelButton @cancel="cancelImport" @confirm="confirmImport"></u-modal>
</template>

<script lang="ts" setup>
	import { computed, reactive, ref } from "vue";
	import { useUserStore } from "../../../stores/useUserStore";
	import { useProduceStore } from "../../../stores/useProduceStore";
	import { getTimes } from "../../../utils/common";
	import { useDictionaryStore } from "../../../stores/useDictionaryStore";
	import { http } from "../../../utils/http";
	// 表单数据定义
	const umodel = ref({
		unscheduledReportId: "",
		unscheduledReportCode: "",
		plantCode: "",
		workCenterName: "",
		crewName: "",
		unscheduledReportType: "",
		unscheduledReportTypeName: "",
		unscheduledReportContent: "",
		completeTime: getTimes(Date.now()),
		startTime: getTimes(Date.now()),
		completeTimeA: getTimes(Date.now()),
		startTimeA: getTimes(Date.now()),
		totalTime: "",
	});
	const show = ref(false);
	const show1 = ref(false);

	const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
	console.log("loginWorkInfo", loginWorkInfo.value)
	// 班组信息获取
	let crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
	console.log('工厂', crewMemberList.value)
	//非生产报工数据
	umodel.value.plantCode = crewMemberList.value[0].plantCode + "-" + crewMemberList.value[0].plantName
	umodel.value.workCenterName = loginWorkInfo.value.workCenterName
	umodel.value.crewName = loginWorkInfo.value.crewName
	// 表单规则定义
	const rules = ref({
		unscheduledReportContent: [
			{
				type: "string",
				message: "请输入数字",
				trigger: ["blur", "change"],
			},

		],
		unscheduledReportTypeName: [
			{
				required: true,
				type: "string",
				message: "请选择非生产报工类型",
				trigger: ["blur", "change"],
			},
		],
		totalTime: [
			{
				required: true,
				type: "number",
				message: "请输入中断时长",
				trigger: ["blur", "change"],
			},
			{
				validator: (rule, value, callback : (a ?: any) => {}) => {
					if (value) {
						if (/^\d+$/.test(value)) {
							//验证正整数和0的正则
							return true;
						} else {
							return false;
						}
					} else {
						return false;
					}
				},
				message: "中断时长不是为负数",
			},
		]
	});
	//根据时间戳计算时分秒
	function calculateDuration() {
		const start = new Date(umodel.value.startTime);
		const end = new Date(umodel.value.completeTime);
		const duration = end.getTime() - start.getTime(); // 毫秒

		const days = Math.floor(duration / (1000 * 60 * 60 * 24));
		const hours = Math.floor((duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
		const seconds = Math.floor((duration % (1000 * 60)) / 1000);
		// umodel.value.totalTime = Math.floor((duration / (1000 * 60)));
		times.value = Math.floor((duration / (1000 * 60)));
		if (times.value <= 0) {
			uni.$u.toast('完工时间需大于开工时间');
		}
		return { days, hours, minutes, seconds };
	}
	const props = defineProps({
		result: {
			type: String,
		},
	});
	let one = JSON.parse(props.result)
	let title = ref()
	let times = ref()
	if (one.unscheduledReportId) {
		console.log("one", one)
		umodel.value = one
		//时间控件时间设置
		umodel.value.completeTimeA = getTimes(Date.now())
		umodel.value.startTimeA = getTimes(Date.now())
	} else {
		title.value = one
	}

	// 校验提交
	const uForm = ref();
	const posting = ref(false);
	function submit() {
		if (times.value <= 0 || umodel.value.completeTime == umodel.value.startTime) {
			uni.$u.toast('完工时间需大于开工时间');
			return
		}
		uForm.value
			.validate()
			.then(async (res) => {
				console.log(title.value)
				if (one.unscheduledReportId) {
					const res = await http({
						url: '/mes/mesunscheduledreportplan/save',
						method: 'POST',
						data: umodel.value
					});
					if (res.code == "200") {
						uni.$u.toast('编辑成功！');
					}
					uni.navigateBack({
						delta: 1, //返回层数，2则上上页
					})
					posting.value = true;
				}
				if (title.value.id) {
					umodel.value.unscheduledReportId = title.value.id
					umodel.value.unscheduledReportCode = title.value.unscheduledReportCode
					const res = await http({
						url: '/mes/mesunscheduledreportplan/save',
						method: 'POST',
						data: umodel.value
					});
					if (res.code == "200") {
						uni.$u.toast('填报成功！');
					}
					uni.navigateBack({
						delta: 1, //返回层数，2则上上页
					})
					posting.value = true;
				} else {
					title.value.detailsPlan = [umodel.value]
					console.log(umodel.value)
					const res = await http({
						url: '/mes/mesunscheduledreport/save',
						method: 'POST',
						data: title.value
					});
					if (res.code == "200") {
						uni.$u.toast('创建成功！');
					}
					uni.navigateBack({
						delta: 1, //返回层数，2则上上页
					})
					posting.value = true;
				}
			})
			.catch((errors) => {
				console.log(errors);
			});
	}
	async function deleted() {
		showImport.value = true;
	}
	const storageLocationShow = ref(false);
	//获取字典
	let storageLocationList = reactive([]);
	storageLocationList[0] = useDictionaryStore().filterDictList("ReportType")
	//报工类型
	const handelStorageLocation = (e) => {
		let item = e.value[0];
		umodel.value.unscheduledReportType = item.value;
		umodel.value.unscheduledReportTypeName = item.label;
		storageLocationShow.value = false;
	};


	// 时间选择
	function timeSelect(e) {
		console.log(e);
		umodel.value.startTimeA = e.value
		umodel.value.startTime = getTimes(e.value);
		calculateDuration()
		console.log(umodel.value.startTime);
		show.value = false;
	}
	function timeSelect1(e) {
		console.log(e);
		umodel.value.completeTimeA = e.value
		umodel.value.completeTime = getTimes(e.value);
		console.log(umodel.value.completeTime);
		calculateDuration()
		show1.value = false;
	}
	function openTimeSelect() {
		show.value = true;
		uni.hideKeyboard();
	}
	function openTimeSelect1() {
		show1.value = true;
		uni.hideKeyboard();
	}

	// 选择订单
	const selectOrder = ref({});
	const selectIndex = ref();
	const selectState = ref()
	const showImport = ref(false);
	// 取消选择订单
	function cancelImport() {
		showImport.value = false;
		selectOrder.value = {};
		selectIndex.value = null;
		selectState.value = "";
	}
	// 确定
	async function confirmImport() {
		const res = await http({
			url: '/mes/mesunscheduledreportplan/delete',
			method: 'POST',
			data: { ids: [one.id] }
		});
		if (res.code == "200") {
			uni.$u.toast('删除成功！');
			uni.navigateBack({
				delta: 1, //返回层数，2则上上页
			})
			showImport.value = false;
		}
	}
</script>

<style lang="scss">
	.baseForm {
		.form {
			padding: $uni-page-padding;
		}

		.u-form-item {
			min-height: 46px;
		}

		:deep(.uicon-arrow-right) {
			top: 1px;
			margin-left: 3px;
		}

		.submit_btn {
			margin: 60rpx;
			border-radius: 60rpx;
		}

		:deep(.u-form-item__body__right__content__slot) {
			flex-direction: row-reverse;
		}

		:deep(.u-textarea__field) {
			text-align: right;
		}

		.u-textarea {
			border: 1px solid $uni-input-border-color;
			border-radius: 8px;
		}
	}
</style>